import axios from 'axios';
// import router from '../router/index';
import cookie from 'cookiejs';
import jwt from 'jsonwebtoken';
import {HashRouter} from 'react-router-dom'
import * as env from '../api/environment'
const router = new HashRouter()
const baseUrl = env[process.env.NODE_ENV].baseUrl
console.log(baseUrl)
// 创建axios实例
const http = axios.create({
  // baseURL: process.env.BASE_API, // api的base_url
  // baseURL: 'http://172.16.110.166:8089/',
  baseURL: '',
  timeout: 15000, // 请求超时时间
});

// http request 拦截器 用于发送token等
http.interceptors.request.use(
  (c) => {
    jwt.verify(cookie('zp_token'), 'token', (err, res) => {
      if (!err) {
        // if (to.name === 'login') router.push('')
      } else {
        cookie.remove('zp_token')
        if (router.history.location.pathname !== '/login') {
          router.history.push('/login')
        }
      }
    })
    // if (cookie('zp_token') && (jwt.verify(cookie('zp_token'), 'token').account)) {
    //   c.headers.auth = cookie('zp_token');
    // } else {
    //   if (router.history.location.pathname !== '/login') {
    //     router.history.push('/login')
    //   }
    // }
    return c;
  }
);

// http respons 拦截器 用于统一错误处理等
http.interceptors.response.use(

  (response) => {
    // if (vue.$vux.loading) vue.$vux.loading.hide()
    return response.data;
  },

  (error) => {
    if (error.message.indexOf('Network Error') >= 0 || error.message.indexOf('timeout of 3000ms exceeded') >= 0) {
      // router.push('404');
      // router.history.push('/404')
      // location.href = '/#/maintain';
      return Promise.reject(error.message);
    }

    // if (error.response) {
    //   switch (error.response.data.message) {
    //     // case ErrorCode.TOKEN_INVALID:
    //     // store.dispatch('clearTokenInfo', true);
    //     // wxAuth()
    //     // break
    //   }
    //   throw new Error(error.response.data.message);
    // }
  }
);
const ajax = {
  post(url, params) {
    return new Promise((resolve, reject) => {
      http.post(baseUrl + url, params).then((res) => {
        resolve(res);
      }).catch((error) => {
        reject(error)
        console.log(error)
      });
    });
  },
  get(url, params) {
    return new Promise((resolve, reject) => {
      http.get(baseUrl + url, params).then((res) => {
        resolve(res);
      }).catch((error) => {
        reject(error)
        console.log(error)
      });
    });
  },
};
export default ajax;
